<!--
 * @description: 跨域页面fetch
 * @Author: lhr
 * @Date: 2020-10-27 17:16:25
 * @LastEditors: lhr
 * @LastEditTime: 2020-10-30 15:35:02
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>跨域fetch</title>
    <style>
      div {
        margin: 10px 0;
      }
      button {
        border: 1px solid #ec7259;
        padding: 5px;
        background: #fff;
        border-radius: 5px;
        color: #ec7259;
      }

      input[type="text"],
      input[type="password"] {
        height: 30px;
        line-height: 30px;
        border-radius: 5px;
        border: 1px solid #aaa;
        padding: 0 5px;
      }
    </style>
  </head>
  <body>
    <div>
      <input type="text" id="pId" />
      <button type="button" onclick="getDetail()">get请求 - error</button>
    </div>

    <script>
      function getDetail() {
        var id = document.getElementById("pId").value;
        fetch("http://localhost:3000/detail?id=" + id)
          .then(function (res) {
            if (res.ok) {
              return res.json();
            }
            throw new Error(res);
          })
          .then((myJson) => {
            console.log("getDetail ok", myJson);
          })
          .catch((err) => {
            console.log("getDetail error", err);
          });
      }
    </script>

    <div>
      <input type="text" id="pIdCors" />
      <button type="button" onclick="getCorsDetail()">
        简单跨域get请求 - ok
      </button>
    </div>
    <script>
      function getCorsDetail() {
        var id = document.getElementById("pIdCors").value;
        fetch("http://localhost:3000/detailCors?id=" + id)
          .then(function (res) {
            if (res.ok) {
              return res.json();
            }
            throw new Error(res);
          })
          .then((myJson) => {
            console.log("getCorsDetail ok", myJson);
          })
          .catch((err) => {
            console.log("getCorsDetail error", err);
          });
      }
    </script>

    <div>
      <form name="loginForm">
        <input type="text" placeholder="用户名" name="username" />
        <input type="password" placeholder="密码" name="password" />
        <input type="file" placeholder="头像" name="photo" />
        <div>
          <button type="button" onclick="login()">
            简单请求-跨域文本post登录 - ok
          </button>
          <button
            type="button"
            onclick="login('application/x-www-form-urlencoded')"
          >
            简单请求-跨域表单post登录 - ok
          </button>
        </div>
        <div>
          <button type="button" onclick="login('application/json',true)">
            非简单请求-跨域json post登录 - error
          </button>
          <button
            type="button"
            onclick="login('application/json',true,'login2')"
          >
            非简单请求-跨域json post登录(后台设置允许头Content-Type) - ok
          </button>
        </div>
        <div>
          <button type="button" onclick="login('multripart/form-data')">
            非简单请求-跨域formData post登录 - error
          </button>
          <button
            type="button"
            onclick="login('multripart/form-data',false,'login2')"
          >
            非简单请求-跨域formData post登录(后台设置允许头Content-Type) - ok
          </button>
        </div>
        <div>
          <button
            type="button"
            onclick="login('',false,'login','8ks9j3hsyh201dgeyan887yhgf')"
          >
            非简单请求-跨域文本post登录(自定义头token) - error
          </button>
          <button
            type="button"
            onclick="login('',false,'login3','8ks9j3hsyh201dgeyan887yhgf')"
          >
            非简单请求-跨域文本post登录(自定义头token，后台允许头token) - ok
          </button>
        </div>
        <div>
          <button
            type="button"
            onclick="login('application/json',true,'login4','8ks9j3hsyh201dgeyan887yhgf')"
          >
            非简单请求-跨域json post登录(自定义头token，后台允许头token) - ok
          </button>
        </div>
        <div>
          <button type="button" onclick="login('',false,'login','',true)">
            跨域携带cookie-origin* - error
          </button>
        </div>
        <div>
          <button type="button" onclick="login('',false,'login5','',true)">
            跨域携带cookie-origin非* - error
          </button>
        </div>
        <div>
          <button type="button" onclick="login('',false,'login6','',true)">
            跨域携带cookie-origin非*允许cookie - ok
          </button>
        </div>
      </form>
    </div>
    <script>
      function login(
        ct = "",
        isJSON = false,
        path = "login",
        token = "",
        useCookie
      ) {
        var myHeaders = new Headers();
        if (ct) {
          myHeaders.append("Content-Type", ct);
        }
        if (token) {
          myHeaders.append("token", token);
        }
        var postData;
        if (isJSON) {
          postData = JSON.stringify({
            username: loginForm.username.value,
            password: loginForm.password.value,
          });
        } else if (ct === "multripart/form-data") {
          postData = new FormData();
          postData.append("username", loginForm.username.value);
          postData.append("password", loginForm.password.value);
          postData.append("photo", loginForm.photo.files[0]);
        } else {
          postData = `username=${loginForm.username.value}&password=${loginForm.password.value}`;
        }
        fetch("http://localhost:3000/" + path, {
          method: "POST",
          headers: myHeaders,
          credentials: useCookie ? "include" : "same-origin", // 不设置这个的话，跨域请求默认不带cookie
          body: postData,
        })
          .then(function (res) {
            if (res.ok) {
              return res.json();
            }
            throw new Error(res);
          })
          .then((myJson) => {
            console.log("login ok", myJson);
          })
          .catch((err) => {
            console.log("login error", err);
          });
      }
    </script>
  </body>
</html>
